package newcoder.t5;

//数字以 0123456789101112131415... 的格式作为一个字符序列，在这个序列中第 2 位（从下标 0 开始计算）是 2 ，第 10 位是 1 ，第 13 位是 1 ，以此类题，请你输出第 n 位对应的数字。
public class Solution {

    static int[] ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    int index = 0;

    int max = 0;

    boolean running = true;

    int result = 0;

    public int findNthDigit(int n) {
        if (n <10){
            return ints[n];
        }
        max = n;
        // write code here
//        char[] chars = {'0','1','2','3','4','5','6','7','8','9'};
        int length = 0;
        while (running) {
            length++;
            int start = length == 1 ? 0 : 1;
            int[] temp = new int[length];
            for (int i = start; i < 10; i++) {
                back(0, length, i, temp);
            }
        }
        return result;
    }

    public void back(int nextIndex, int length, int target, int[] temp) {
        if (running) {
            if (nextIndex == length - 1) {
                temp[nextIndex] = ints[target];
                if (index == max){
                    result = temp[index-max];
                    running = false;
                }
                 else if (index+length>max){
                    result = temp[(index+length)-max];
                    running = false;
                }
                index+=length;
                return;
            }
            for (int i = 0; i < 10; i++) {
                temp[nextIndex] = ints[target];
                back(nextIndex + 1, length, i, temp);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int nthDigit = solution.findNthDigit(11);
        System.out.println(nthDigit);
    }
}
